<?php 
class consignment extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->model('mglobal');
    $this->load->model('mmaster');
    $this->load->model('mconsignment');
    $this->load->library('enc');
    $this->load->library('form_validation');
    $this->mglobal->is_logged_in();
  }

  public function index() {
    $template          = "shell/smooth";
    $data["main_view"] = "trans/consignment";
    $this->load->view($template, $data);
  }

  public function add()
  {
    $this->load->model('msell');

    $template          = "shell/smooth";
    $data["main_view"] = "trans/consignment_create";
    $data["sales_id"]  = $this->msell->sell_in_sales_team($this->session->userdata('cluster_id'));
    $data["termin"]    = $this->mconsignment->termins();

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region'] = $teritori[0];
    $data['cluster'] = $teritori[1];

    $this->form_validation->set_rules('trx_date',         'Tanggal Transaksi', 'required');
    $this->form_validation->set_rules('sales_id',         'Nama Sales',        'required');
    $this->form_validation->set_rules('partner_id',       'Nama Partner',      'required');
    $this->form_validation->set_rules('iccid[]',          'Item',              'required');
    $this->form_validation->set_rules('program_nasional', 'Program Nasional',  'required');
    $this->form_validation->set_rules('term_of_payment',  'Termin Konsinyasi', 'required');

    $trx_date     = $this->input->post("trx_date");
    $partner_id   = explode("_", $this->input->post("partner_id"));
    $sales_id     = explode("_", $this->input->post("sales_id"));
    $iccid        = $this->input->post('iccid');
    $top_id       = $this->input->post("term_of_payment");
    $remark       = $this->input->post("remark");

    $program_id[] = $this->input->post("program_nasional");
    $programC     = $this->input->post("program_cluster");
    if($programC)
      { $program_id[] = $programC; }

    $dup_iccid = array(); $new_iccid = array();

    // print_r(array($trx_date, $partner_id, $sales_id, $iccid, $top_id)); die();

    if ($this->form_validation->run() != FALSE)
    {
      $duplicate_iccid = array_count_values($iccid);    // Returns ['iccid_0']=>counts, [iccid_1]=>counts
      $unique_iccid    = array_unique($iccid);          // Returns [0]=>"iccid_0", [1]=>"iccid_1"
      $duplicate_iccid; 
      $unique_iccid; 
      foreach ($unique_iccid as $key) {   // $key become unique_iccid value: iccid_0, iccid_1
        if($duplicate_iccid[$key] == 1) 
          { $new_iccid[] = $key; }        // if the count equal to 1, create new array, the array is now unique
        else 
          { $dup_iccid[] = $key; }        // if the count greater then to 1, create new array contains unique iccid above.
      }

      $iccidsama='';
      foreach ($dup_iccid as $a)
        { $iccidsama .= $a.', '; }

      // Validate each unique iccids and return as new array named valid_iccid
      $i = 0;
      $valid_iccid = array();
      $valid_iccid = $new_iccid;
      // foreach ($new_iccid as $key) { 
      //   $valid_iccid[] = $this->_validate_item($key, $sales_id[1], $partner_id[0]); 
      //   if ($valid_iccid[$i] == null)
      //     { unset($valid_iccid[$i]) ;}
      //   $i++;
      // }

      if (count($valid_iccid) != 0 ) { 
        $db_sri = $this->load->database('Retails', TRUE);
        $this->db->trans_begin();
        // ($sales_id, $territory_id, $top_id, $trx_date, $remark)
          $trx_id = $this->mconsignment->save_consignment( $sales_id[1], $partner_id[0], $top_id, $trx_date, $remark, 
                                                           $this->session->userdata('cluster_id'), 
                                                           $this->session->userdata('region_id') );
          foreach ($program_id as $program) 
            { $this->mconsignment->consignment_program($trx_id, $program); }
          foreach ($valid_iccid as $item) 
            { $this->mconsignment->save_consignment_detail($trx_id, $item); }

          $db_sri->trans_begin();
          $this->load->model('mintegrasi');
          $this->mintegrasi->StockIn($partner_id[1], $valid_iccid, $trx_id, 'consignment');

          $log = array('consignment_id' => $trx_id, 'program_id' => $program_id, 'ICCID' => $valid_iccid, 
                       'cluster_id' => $this->session->userdata('cluster_id'), 'region_id' => $this->session->userdata('region_id') );
          $this->mglobal->saveLog('consignment', 'create', json_encode($log));

        if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE) { 
          $this->db->trans_rollback(); 
          $db_sri->trans_rollback();
          $this->session->set_flashdata('div_class', 'error');
          $this->session->set_flashdata('messege', 'Transaksi gagal disimpan. Kesalahan koneksi atau tidak ada item yang valid ');
          redirect(base_url() . "index.php/consignment");
        }
        else { 
          $this->db->trans_commit(); 
          $db_sri->trans_commit();
          $this->session->set_flashdata('div_class', 'success');
          if (count($dup_iccid) != 0) { $message = "Data berhasil disimpan dengan nomor transaksi $trx_id, terdapat duplikat ICCID: $iccidsama" ; }
          else {$message = "Data berhasil disimpan dengan nomor transaksi $trx_id " ; }
          $this->session->set_flashdata('messege', $message);
          redirect(base_url() . "index.php/consignment");
        }
      } // end of proses simpan
    } // end of form validation true
    else
    {
      $this->load->view($template, $data);
    }

  } // end of add()

  private function _validate_item($iccid, $sales_id, $partner_id)
  {
    $item =  $this->mconsignment->validate_item($iccid, $sales_id, $partner_id);
    return $item;
  }

  public function detail($eId)
  {
    $data['template']   = "shell/smooth";
    $data['main_view']  = 'trans/consignment_detail';

    $trx_id = $this->enc->defog($eId);

    $data['detail'] = $this->mconsignment->detail($trx_id);
    $data['items']  = $this->mconsignment->items($trx_id);
    // echo $this->db->last_query();
    $this->load->view($data['template'], $data);  
  }

  public function takeout()
  {
    $trx_id     = $this->enc->defog($this->input->post('trx_id'));
    $itemStatus = $this->input->post("status");
    $items      = $this->input->post("iccid");
    $db_sri     = $this->load->database('Retails', TRUE);

    $this->db->trans_start();

      $this->mconsignment->takeout($trx_id);
        $sold=0; $unsold=0;
        $stat=array(); $item=array();
        foreach ($itemStatus as $status) {
          $stat[] = $status;
          if($status == 0) {$sold++;}
          else {$unsold++;}
        }
        foreach ($items as $iccid) { $item[] = $iccid; }

        // print_r($itemStatus); print_r($items);

      $solditems = array(); $unsolditems = array();
      for ($i=0; $i < count($items); $i++) { 
        if ($stat[$i] == 0) 
         { $solditems[] = $item[$i]; }    // ini barang yang kejual
        elseif ($stat[$i] == 1) 
          { $unsolditems[] = $item[$i]; } // ini barang yang tidak terjual
      }

      if(count($solditems) != 0) {
        $invalid_iccid = $this->mconsignment->validate_iccid_for_sellin($solditems);
        $valid_iccid = array_diff($solditems, $invalid_iccid);

        if(count($valid_iccid) != 0) {  // ada yang terjual
          $newSellIn = $this->mconsignment->createSellIn($trx_id); 
          $this->mconsignment->sellInDetail($newSellIn, $valid_iccid, $trx_id);
          $log[] = array(
              'trx_id' => $trx_id,
              'detail' => 'sold consignment', 
              'iccid'  => $valid_iccid,
            );
        }
      }

      if(count($unsolditems) != 0) { 
        $this->mconsignment->normalize($trx_id, $unsolditems); 
        $log[] = array(
            'trx_id' => $trx_id,
            'detail' => 'unsold consignment', 
            'iccid'  => $unsolditems,
          );
      }

      $this->mglobal->saveLog('consignment', 'takeout', json_encode($log));
      if (count($solditems)   != 0 ) 
        { $this->session->set_flashdata('messege1', json_encode($solditems).' item terjual, telah tercatat sebagai Sell In. '); }
      if (count($unsolditems) != 0 ) { 
        $this->session->set_flashdata('messege2', json_encode($unsolditems).' item tidak terjual, telah dicatat untuk pengembalian ');
        $db_sri->trans_begin();
        $this->load->model('mintegrasi');
        $this->mintegrasi->StockOut($unsolditems, 'consignment_'.$trx_id, 'consignment');
      }
    
        if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE) {
          $this->db->trans_rollback();
          $db_sri->trans_rollback();
        } else {
          $this->db->trans_commit();
          $db_sri->trans_commit();
          $this->session->set_flashdata('div_class', 'success');
          redirect("index.php/consignment");
        }
  }

  public function dataList()
  {

    $cluster_id = $this->session->userdata('cluster_id');
    $aColumns = array('cc.consignment_id','cast(cc.consignment_date as text) as trx_date','cc.user_id','f_get_user(cc.user_id) as user_name',
                      'f_get_channel_id_by_territory_id(tt.territory_id) as partner_id','tt.territory_name',
                      'DATE(cc.consignment_date) + ct.term_day as due_date','cc.istatus'
                     );
    $sIndexColumn = "cc.consignment_id";
    $sTable = " t_trx_consignment cc join t_mtr_consignment_term ct on ct.term_id = cc.term_id join t_mtr_territory tt on tt.territory_id = cc.territory_id ";

    $sLimit = "";

    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
      $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
        intval( $_GET['iDisplayStart'] );
    }

    if ( isset( $_GET['iSortCol_0'] ) )
    {
      $sOrder = "ORDER BY  ";
      for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
        if(substr($aColumns[ intval( $_GET['iSortCol_'.$i] ) ], 0, 4) == 'cast') {
          $x_order = explode(') as ', $aColumns[ intval( $_GET['iSortCol_'.$i] ) ] );
          $sOrderBy = $x_order[0].')';
        }
        else {
          $x_order = explode(' as ', $aColumns[ intval( $_GET['iSortCol_'.$i] ) ] );
          if(count($x_order) > 1) 
            { $sOrderBy = $x_order[1]; }
          else 
            { $sOrderBy = $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]; }
        }

        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
        {
          $sOrder .= $sOrderBy."
            ".($_GET['sSortDir_'.$i]==='desc' ? 'asc' : 'desc').", ";
        }
      }

      $sOrder = substr_replace( $sOrder, "", -2 );
      if ( $sOrder == "ORDER BY " )
        { $sOrder = ""; }
    }
     
    $sWhere = " WHERE tt.parent_id = $cluster_id ";
    if ( $_GET['sSearch'] != "" )
    {
      $sWhere = "WHERE tt.parent_id = $cluster_id AND (";
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $_GET['bSearchable_'.$i] == "true" )
          { 
            if(substr($aColumns[$i], 0, 4) == 'cast') {
              $x_where = explode(') as ', $aColumns[$i]);
              $sWhereIs = $x_where[0].')';
            }
            else { 
              $x_where = explode(' as ', $aColumns[$i]);
              if(count($x_where) > 1)
                { $sWhereIs = $x_where[0]; }
              else 
                { $sWhereIs = $aColumns[$i]; }
            }
            $sWhere .= $sWhereIs." ILIKE '%".( $_GET['sSearch'] )."%' OR "; 
          }
      }
      $sWhere = substr_replace( $sWhere, "", -3 );
      $sWhere .= ")";
    }
     
    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != null )
      {
        if ( $sWhere == "" )
          { $sWhere = "WHERE "; }
        else
          { $sWhere .= " AND "; }
        $sWhere .= $aColumns[$i]." ILIKE '%".($_GET['sSearch_'.$i])."%' ";
      }
    }
     
    $sQuery = "
      SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
      FROM   $sTable
      $sWhere
      $sOrder
      $sLimit
    ";
    $rResult = $this->db->query($sQuery); 
    // $rResult->result_array();
    $sQuery = "
      SELECT COUNT (*) AS numrows
      FROM   $sTable
      WHERE tt.parent_id = $cluster_id
    ";
    $rResultTotal = $this->db->query($sQuery)->row(); 
    $iTotal = $rResultTotal->numrows;
     
    if ( $sWhere != "" )
    {
        $sQuery = "
          SELECT COUNT (*) AS numrows
          FROM   $sTable
          $sWhere
        ";
        $rResultFilterTotal = $this->db->query($sQuery)->row(); 
        $iFilteredTotal = $rResultFilterTotal->numrows;
    }
    else
    { $iFilteredTotal = $iTotal; }

    // Generating outputs
    $output = array(
      "sEcho" => intval($_GET['sEcho']),
      "iTotalRecords" => $iTotal,
      "iTotalDisplayRecords" => $iFilteredTotal,
      "aaData" => array()
    );

    // $j=$_GET['iDisplayStart'] ;
    foreach ($rResult->result_array() as $aRow  )
    {
      $row = array();
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $aColumns[$i] != null )
        {
          if(substr($aColumns[$i], 0, 4) == 'cast') {
            $colName = explode(') as ', $aColumns[$i]);
            $colName = $colName[1];
          }
          else {
            $colName = explode(' as ', $aColumns[$i]);
            if(count($colName) > 1 )
              { $colName = $colName[1]; }
            else {
              $colName = explode('.', $aColumns[$i]);
              $colName = $colName[1];
            }
          }
          $row[] = $aRow[ $colName ];
          // foreach ($row as $key) {
          //   $row[0] = $this->enc->fogit($key[0]);
          // }
        }
      }
      $output['aaData'][] = $row;
    }
    echo json_encode( $output );
  }

//process posted form data (the requested items like province)
function load_sell($iccid){
$data['test'] = $this->mconsignmenttitip->getSell($iccid); //Search DB

if('IS_AJAX')
{
echo json_encode($data['test']);
}
}

//proses data untuk halaman detail
function getDetail($id1='', $id2='')
{
$sell_id = $id1;

$temp = $this->mconsignmenttitip->getById($sell_id);
$sales_id = $temp->user_id;

$temp = "";

$temp = $this->mconsignmenttitip->getClusterName($this->session->userdata('username'));
$data['ter_name'] 	= $temp[0]['territory_name'];
$ter_id 			= $temp[0]['territory_id'];

$list = $this->pdfAndDetail($sell_id, $ter_id);
$data['strId'] = $list[0];
$data['dist'] = $list[1];
$data['sell_in'] = $list[2];
$data['sales_name'] = $list[3];
$data['sell_in_detail'] = $list[4];		
//$data['outlet_name'] = $data['sell_in']->channel_id;
$data['outlet_name'] = $this->mconsignmenttitip->getPartner($data['sell_in']->channel_id);


$data['program_ho'] = $this->mconsignmenttitip->getDetailProgram($sell_id, "ho", $sales_id);
$data['program_cluster'] = $this->mconsignmenttitip->getDetailProgram($sell_id, "cl", $sales_id);

for($ii=0;$ii<count($list[4]);$ii++)	
{
$data['itemDetail'][$ii] = $list[5+$ii];
$data['detailCounter'] = $ii + 1;
}

$data['template'] 	= "shell/smooth";
$data['main_view']  = 'f-sell-detail';
$this->load->view($data['template'],$data);


}

//proses data untuk men-generate file pdf dan detail view
function pdfAndDetail($sell_id, $ter_id)
{
$list = array();

$list[0] = $this->concateId($sell_id);

$this->db->select('distributor_name, distributor_address');
$this->db->where('territory_id', $ter_id);
$q = $this->db->get('t_mtr_distributor');
$list[1] = $q->result_array();				
$list[2] = $this->mconsignmenttitip->getById($sell_id);				
$list[3] = $this->mconsignmenttitip->getNikName($list[2]->user_id);		

$this->db->select('*');
$this->db->where('sell_in_id', $sell_id);
$q = $this->db->get('t_trx_sell_in_detail');
$list[4] = $q->result_array();

for($ii=0;$ii<count($list[4]);$ii++)
{
$list[$ii+5] = $this->mconsignmenttitip->getItemDetail($list[4][$ii]['iccid']);
}

return $list;

}
}